<template>
  <view class="example">
    <uni-forms ref="baseForm" :modelValue="baseFormData">
      <view class="avatar-container">
        <view class="set-avatar" @click="uploadAvatar">
          <image class="noAvatar" src="/static/noAvatar.png"/>
          <image class="avatar" :src="baseFormData.avatar"/>
          <view class="avatar-text">上传头像</view>
        </view>
      </view>
      <uni-forms-item label="用户昵称" required name="name">
        <uni-easyinput v-model="baseFormData.name" placeholder="请输入用户昵称" />
      </uni-forms-item>
      <uni-forms-item label="所在地区" required name="location">
        <view class="locate">
          <text class="tx">{{baseFormData.location}}</text>
          <uni-icons type="location" size="30" class="icon" @click="requireLocate"></uni-icons>
        </view>
      </uni-forms-item>
	  <uni-forms-item label="手机号" required name="phoneNum">
	    <uni-easyinput v-model="baseFormData.phoneNum" placeholder="请输入手机号" />
	  </uni-forms-item>
      <uni-forms-item label="密码" required name="pass">
        <uni-easyinput v-model="baseFormData.pass" placeholder="请输入密码" type="password" />
      </uni-forms-item>
      <uni-forms-item label="确认密码" required name="repass">
        <uni-easyinput v-model="baseFormData.repass" placeholder="请再次输入密码" type="password" />
      </uni-forms-item>
      <!-- <uni-forms-item label="真实姓名" name="actualName">
        <uni-easyinput v-model="baseFormData.actualName" placeholder="请输入真实姓名" />
      </uni-forms-item> -->
      <!-- <uni-forms-item label="身份证号" name="idCard">
        <uni-easyinput v-model="baseFormData.idCard" placeholder="请输入身份号码" />
      </uni-forms-item> -->
      
      <uni-forms-item label="短信验证码" name="checkNum">
        <view class="message">
          <uni-easyinput v-model="baseFormData.checkNum" placeholder="请输入短信验证码" />
          <code-btn :is-valid="isPhoneValid" @validate-phone="validatePhoneNum" @syncCode="syncCode"></code-btn>
        </view>

      </uni-forms-item>
    </uni-forms>
    <button type="primary" @click="submit('baseForm')">提交</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      baseFormData: {
        name: '',
        location: '',
        pass: '',
        repass: '',
        actualName: '',
        idCard: '',
        phoneNum: '',
        checkNum: '',
        latitude:0,
        longitude:0,
        avatar: '',
        images: [],
      },
      isPhoneValid: '', // 手机号是否有效的标志位
      checkNum: '',
      customRules: {
        name: {
          rules: [{
            required: true,
            errorMessage: '请填写店铺名',
          }]
        },
        location: {
          rules: [{
            required: true,
            errorMessage: '请填写所在地区',
          }]
        },
        pass: {
          rules: [{
            required: true,
            errorMessage: '请输入密码',
          }]
        },
        repass: {
          rules: [{
            required: true,
            errorMessage: '请再次输入密码',
          }, {
            validateFunction: (rule, value, data, callback) => {

              if (value != data.pass) {
                callback('两次密码输入不一致')
              }
            }
          }]
        },
        phoneNum: {
          rules: [{
                required: true,
                errorMessage: '手机号码不能为空',
              },
              {
                validateFunction: (rule, value, data, callback) => {
                  console.log(value, data, rule, callback)
                  const regExp = /^[1]([3-9])[0-9]{9}$/;
                  if (!regExp.test(value)) {
                    // 手机号格式不正确，调用 callback 返回错误信息
                    callback('手机号格式不正确');
                    this.isPhoneValid = false
                  } else {
                    // 手机号格式正确，调用 callback 不传递参数
                    callback();
                    this.isPhoneValid = true;
                  }
                }
              }
            ]
          },
          checkNum: {
            rules: [{
                required: true,
                errorMessage: '验证码不能为空',
              },
              {
                validateFunction: (rule, value, data, callback) => {
                  console.log(value, data, rule, callback)
                    
                  if (this.checkNum != value) {
                    // 手机号格式不正确，调用 callback 返回错误信息
                    callback('验证码不正确');

                  } else {
                    // 手机号格式正确，调用 callback 不传递参数
                    callback();
                  }
                }
              }
            ]
          }
        },
      }
    },
    onReady() {
      // 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
      this.$refs.baseForm.setRules(this.customRules)
    },
    methods: {
      uploadAvatar() {
        // 选择图片
        uni.chooseImage({
          count: 1,
          sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
          success: (chooseImageRes) => {
            const tempFilePaths = chooseImageRes.tempFilePaths;
            // 上传图片
            uni.uploadFile({
              url: "http://localhost:8000/upload", // 后端接口路径
              filePath: tempFilePaths[0],
              name: "file",
              formData: {
                user: "test",
              },
              success: (uploadRes) => {
                console.log("上传成功", uploadRes.data);
                // 解析服务器返回的 JSON 数据，提取图片路径
                const responseData = JSON.parse(uploadRes.data);
                if (responseData.code === 200) {
                  this.images = [];
                  this.images.push(responseData.data);
                  this.baseFormData.avatar = responseData.data; // 更新 avatar 字段
                } else {
                  console.error("上传失败", responseData);
                }
              },
              fail: (err) => {
                console.error("上传失败", err);
              },
            });
          },
        });
      },
      validatePhoneNum() {
        this.$refs.baseForm.validateField('phoneNum').then((res) => {
          this.isPhoneValid = true;
          
        }).catch((err) => {

          this.isPhoneValid = false;
          // 手机号验证不通过，不执行获取验证码的逻辑
          // ...错误处理逻辑...
        });

      },
      syncCode(e) {
        this.checkNum = e;

      },
      submit() {
        uni.showLoading()
        this.$refs.baseForm.validate().then(async res => {
          uni.hideLoading()
          res.latitude = this.baseFormData.latitude
          res.longitude = this.baseFormData.longitude
          res.avatar = this.baseFormData.avatar // 确保 avatar 字段被正确设置
          const data = await uni.$http.post("/farmer/register", res)
          console.log(data)
          if (data.data.code == 200 && data.data.data == '账号注册成功') {
            uni.showToast({
              title: '账户注册成功',
              icon: 'success', //将值设置为 success 或者 ''
              duration: 2000 //持续时间为 2秒
            })
            this.baseFormData = {
              name: '',
              location: '',
              pass: '',
              repass: '',
              actualName: '',
              idCard: '',
              phoneNum: '',
              checkNum: '',
              longitude: 0,
              latitude: 0,
              avatar: '', // 重置 avatar 字段
              images: [], // 重置 images 数组
            }
            console.log("准备跳转")
            setTimeout(() => {
              uni.navigateTo({
                url: '/subpkg/farmer_login/farmer_login'
              });
            }, 2000);
          } else {
            uni.showToast({
              title: data.data.data,
              icon: 'error', //将值设置为 success 或者 ''
              duration: 2000 //持续时间为 2秒
            })
          }

        }).catch(err => {
          uni.hideLoading()
          console.log('表单错误信息：', err);
        })
      },
      requireLocate() {
        uni.chooseLocation({
          success: (res) => {
            this.baseFormData.location = res.address;
            this.baseFormData.latitude = res.latitude;
            this.baseFormData.longitude = res.longitude;
          }
        });
      }
    },
  };
</script>

<style lang="scss">
  .example {
    
  }

  .uni-forms-item {
    margin: 20px;
    /* 调整表单项间距 */
    background-color: #fff;
    /* 边框颜色 */
    border-radius: 10px;
    /* 边框圆角 */

    .uni-label {
      font-size: 16px;
      /* 标签字体大小 */
      color: #666;
      text-align: center;
      /* 标签字体颜色 */
    }

    .uni-easyinput {
      font-size: 16px;
      /* 输入框字体大小 */
    }

    .uni-input {
      border: none;
      /* 移除输入框边框 */
    }

    .uni-icon-clear {
      color: #999;
      /* 清除按钮颜色 */
    }

    .locate {
      display: flex;
      height: 100%;
      flex: 1;
      text-align: center;

      .icon {
        text-align: right;
        padding-right: 10rpx;
      }

      .tx {
        width: 100%;
        height: 100%;
        padding-left: 5px;
        display: flex;
        align-items: center;
      }
    }
  }

  button {

    margin-top: 30px;


    /* 根据图片调整按钮与表单的间距 */
    width: 80%;
    /* 按钮宽度 */
    height: 50px;
    /* 按钮高度 */
    background-color: #ffe9b2;
    /* 按钮背景颜色 */
    color: white;
    /* 按钮文字颜色 */
    border: none;
    /* 移除边框 */
    border-radius: 5px;
    /* 按钮边框圆角 */
    font-size: 18px;
    /* 文字大小 */
  }

  .message {
    display: flex;
  }

  .set-avatar {
    width: 60px;
    display: flex;
    margin-top: 20px;
    height: 60px;
    justify-content: center;
    align-items: center;



    .avatar-text {
      position: absolute;
      font-size: 13px;
      color: #707070;
      z-index: 2;
    }
  }
  .avatar-container {
  display: flex;
  justify-content: center;
}
.noAvatar {
  z-index: 1;
  position: absolute;
   width: 60px;
      height: 60px;
      border-radius: 50%;
}
.avatar {
  width: 60px;
      height: 60px;
      border-radius: 50%;
  z-index: 3;
}
</style>